package com.qk.management.controller;

import com.qk.code.BusinessEnum;
import com.qk.result.Result;
import com.qk.util.AliOssUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @Author:zhengbowen
 * @Date: 2025/09/01 20:11
 * @Description: 通用控制器
 */
@Slf4j
@RestController
@RequestMapping("")
@RequiredArgsConstructor
public class CommonController {

    private final AliOssUtils aliOssUtils;

    @PostMapping("/upload")
    public Result fileUpload(
            @RequestParam("image") MultipartFile imageFile
    ) {
        if (imageFile == null || imageFile.isEmpty()) {
            return Result.error(BusinessEnum.File_IS_NOT_EXIST);
        }
        if (imageFile.getOriginalFilename() == null || imageFile.getOriginalFilename().trim().isEmpty()) {
            return Result.error(BusinessEnum.File_Name_IS_NOT_NULL);
        }
        try {
            String originalFilename = imageFile.getOriginalFilename();
            String extension = originalFilename != null && originalFilename.lastIndexOf(".") > 0 ?
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
            String objectName = "avatars/"+UUID.randomUUID() + extension;
            String filePath = aliOssUtils.upload(imageFile.getBytes(), objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败:{}", e.getMessage());
            return Result.error(BusinessEnum.File_Load_ERROR);
        }
    }


}
